package com.gidgabs.common.utils;

import com.gidgabs.common.exception.RRException;
import com.gidgabs.config.GidgabsContants;
import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by tby on 2018/7/5.
 */
public class PaypalUtil {
    /**
     * paypal api 接口类
     */
    private APIContext apiContext;

    private RedisTemplate<String, String> redisTemplate;

    public PaypalUtil(APIContext apiContext ,RedisTemplate<String, String> redisTemplate){
        this.apiContext=apiContext;
        this.redisTemplate=redisTemplate;
    }
    public static final Logger LOGGER= LoggerFactory.getLogger(PaypalUtil.class);

    /**
     * paypal预支付,返回地址.以前前端跳转
     * @param money
     * @return
     */
    public String pay(Double money,String orderId) {
        try {
            Payment createdPayment = creatPayment(money).create(apiContext);
            String createdPaymentId = createdPayment.getId();

            //缓存付款id,以便在回调的支付的时候,更改订单状态
            redisTemplate.opsForValue().set(createdPaymentId, orderId);
            Iterator<Links> links = createdPayment.getLinks().iterator();
            while (links.hasNext()) {
                Links link = links.next();
                if (link.getRel().equalsIgnoreCase("approval_url")) {
                    return  link.getHref();
                }
            }
        } catch (PayPalRESTException e) {
            throw new RRException("支付失败"+e);
        }
        throw new RRException("支付失败");
    }


    /**
     * 创建paypal支付对象
     * @param money
     * @return
     */
    private Payment creatPayment(Double money){
        Amount amount = new Amount();
        amount.setCurrency("USD");
        amount.setTotal(String.valueOf(money));

        Transaction transaction = new Transaction();
        transaction.setAmount(amount);
        List<Transaction> transactions = new ArrayList<>();
        transactions.add(transaction);

        Payer payer = new Payer();
        payer.setPaymentMethod("paypal");

        Payment payment = new Payment();
        payment.setIntent("sale");
        payment.setPayer(payer);
        payment.setTransactions(transactions);

        RedirectUrls redirectUrls = new RedirectUrls();
        redirectUrls.setCancelUrl(GidgabsContants.DOMAIN_DNS+GidgabsContants.PAY_PAL_CANCEL_URL);
        redirectUrls.setReturnUrl(GidgabsContants.DOMAIN_DNS+GidgabsContants.PAY_PAL_RETURN_URL);
        payment.setRedirectUrls(redirectUrls);
        return payment;
    }

    /**
     * 调用paypal接口,执行支付,并根据支付结果来处理业务逻辑
     * @param payerID
     * @param paymentId
     * @return
     */
    public boolean executePay(String payerID, String paymentId) {
        Payment payment = new Payment();
        payment.setId(paymentId);

        PaymentExecution paymentExecution = new PaymentExecution();
        paymentExecution.setPayerId(payerID);
        try {
            Payment createdPayment = payment.execute(apiContext, paymentExecution);
            LOGGER.info("支付状态为:"+createdPayment.getState());
            if ("approved".equals(createdPayment.getState())) {//买方批准交易

                // TODO: 2018/7/5 支付成功,执行业务逻辑
                //String saleId = createdPayment.getTransactions().get(0).getRelatedResources().get(0).getSale().getId();
                return true;
            }

        } catch (PayPalRESTException e) {
            LOGGER.error("paypal支付失败:"+e.getDetails().toString());
        }
        return false;
    }
}
